using System;
using System.Collections.Generic;
using System.Text;

namespace Coriander.Xmpp
{
    /// <summary>
    /// Builds XmppMessages
    /// </summary>
    public class MessageBuilder
    {
        StringBuilder buffer    = new StringBuilder();
        Encoding encoding       = null;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="MessageBuilder"></param>
        /// <returns></returns>
        public MessageBuilder AppendIf(Boolean condition, String XmppMessageBuilder)
        {
            if (condition)
            {
                Append(XmppMessageBuilder);
            }

            return this;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MessageBuilder"></param>
        /// <returns></returns>
        public MessageBuilder Append(String XmppMessageBuilder)
        {
            return AppendFormat(XmppMessageBuilder);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public MessageBuilder AppendFormatIf(
            Boolean condition,
            String format,
            params Object[] args
        )
        {
            if (condition)
            {
                AppendFormat(format, args);
            }

            return this;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public MessageBuilder AppendFormat(String format, params Object[] args)
        {
            buffer.AppendFormat(format, args);

            return this;
        }

        /// <summary>
        /// Sets the Encoding on the resulting Message.
        /// </summary>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public MessageBuilder With(Encoding encoding)
        {
            encoding = encoding;
            return this;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="MessageBuilder"></param>
        /// <returns></returns>
        public static implicit operator Message(MessageBuilder builder)
        {
            Message result = new Message(builder.buffer.ToString());
            if (builder.encoding != null)
            {
                result.Encoding = builder.encoding;
            }

            return result;
        }

        /// <summary>
        /// Creates a new MessageBuilder
        /// </summary>
        /// <returns></returns>
        public static MessageBuilder New() { return new MessageBuilder(); }

        public override string ToString()
        {
            return buffer.ToString();
        }
    }
}
